package com.celebriosoftware.client;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkManager {

	private ConnectivityManager manager;

	public NetworkManager(ConnectivityManager manager) {
		this.manager = manager;
	}

	public boolean isNetworkAvailable() {

		//Some vodafone 3g simcards reported not connected, bypassing this
//		NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
//
//		boolean isConnected = activeNetworkInfo != null
//				&& activeNetworkInfo.isAvailable()
//				&& activeNetworkInfo.isConnectedOrConnecting();
//		if (!isConnected) {
//			return false;
//		}
		Boolean isNetworkAvalaible = false;
		try {	
				HttpGet request = new HttpGet(MainActivity.CELEBRIO_URL);

				HttpParams httpParameters = new BasicHttpParams();

				HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
				HttpClient httpClient = new DefaultHttpClient(httpParameters);
				HttpResponse response = httpClient.execute(request);

				int status = response.getStatusLine().getStatusCode();

				if (status == HttpStatus.SC_OK) {
					isNetworkAvalaible = true;
				}

			} catch (SocketTimeoutException e) {
				isNetworkAvalaible = false; // this is somewhat expected
			} catch (UnknownHostException e) {
				isNetworkAvalaible = false;
			} catch (ClientProtocolException e) {
			
				e.printStackTrace();
			} catch (HttpHostConnectException e) {
				isNetworkAvalaible = false;
			} catch (IOException e) {
			
				e.printStackTrace();
			}finally{}
		return isNetworkAvalaible;
	}
}
